package com.cn.stepLock.chain;

import java.util.function.Consumer;

/**
 * @author Aaron
 * @desc
 * @createTime 2022-02-23 22:50
 * @since
 */
public class ChainUtils {

    public static void insertChainIntoTask(Task task,ProcessChain firstChain){
        Task executeTask = task;
        ProcessChain executeChain = firstChain;
        while (executeTask!=null && executeChain!=null){
            executeTask.chain = executeChain;
            executeTask = executeTask.nextChainTask;
            executeChain = executeChain.nextChain;
        }
    }

    public static void startProcessChain(ProcessChain firstProcessChain){
        handleProcessChain(firstProcessChain,ProcessChain::start);
    }

    public static void stopProcessChain(ProcessChain firstProcessChain){
        handleProcessChain(firstProcessChain,ProcessChain::stop);
    }

    public static void handleProcessChain(ProcessChain processChain, Consumer<ProcessChain> chainConsumer){
        ProcessChain executeCahin = processChain;
        while (executeCahin!=null){
            chainConsumer.accept(executeCahin);
            executeCahin = executeCahin.nextChain;
        }
    }

    public static void addChain(ProcessChain preChain, ProcessChain nextChain){
        preChain.nextChain = nextChain;
        nextChain.preChain = preChain;
    }

    public static void addTask(Task preTask,Task nextTask){
        preTask.nextChainTask = nextTask;
        nextTask.preChainTask = preTask;
    }

    public static Thread startThread(Runnable runnable){
         Thread thread = new Thread(runnable);
         thread.start();
         return thread;
    }

}
